import requests
from requests.cookies import RequestsCookieJar
from loguru import logger
import os
import json
import random
import time
import sys
from work.SE_login import se_login

session = requests.Session()
session.headers = {
    "accept": "application/json, text/plain, */*",
    "accept-language": "zh-CN,zh;q=0.9,en;q=0.8",
    "baggage": "sentry-environment=production,sentry-public_key=9b4a6569c04148aa9ab275932e8b1961,sentry-trace_id=6d3c87b36e644447aa41b966f7c05994",
    "cache-control": "no-cache",
    "content-type": "application/x-www-form-urlencoded",
    "origin": "https://online.seranking.com",
    "pragma": "no-cache",
    "priority": "u=1, i",
    "referer": "https://online.seranking.com/admin.site.rankings.site_id-7535981.html?ref=left_menu_clicked",
    "sec-ch-ua": "\"Google Chrome\";v=\"125\", \"Chromium\";v=\"125\", \"Not.A/Brand\";v=\"24\"",
    "sec-ch-ua-mobile": "?0",
    "sec-ch-ua-platform": "\"Windows\"",
    "sec-fetch-dest": "empty",
    "sec-fetch-mode": "cors",
    "sec-fetch-site": "same-origin",
    "sentry-trace": "6d3c87b36e644447aa41b966f7c05994-883ed211bb97959d",
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36",
    "x-requested-with": "XMLHttpRequest"
}


def get_site_se_id(site_id):
    url = f"https://online.seranking.com/api.projects.site.positions.entrypoint.site_id-{site_id}.html"
    retry_count = 0
    while retry_count < 3:
        try:
            res = session.get(url, timeout=5)
        except Exception as e:
            time.sleep(random.randint(1, 2))
            retry_count += 1
            continue
        if res.status_code == 200:
            data = res.json()
            site_se_id = data["data"]["search_engines"][0]["site_engine_id"]
            search_engine_id = data["data"]["search_engines"][0]["search_engine_id"]
            return site_se_id, search_engine_id
        else:
            logger.error(f"请求失败{res.status_code}" )

def get_site_id(company_info, cookies):
    session.cookies = RequestsCookieJar()
    for key, value in cookies.items():
        session.cookies.set(key, value)
    url = "https://online.seranking.com/api.projects.add.html"
    params = {
        "": ""
    }
    data = {
        "site_id": "-1",
        "title": str(company_info["company_name"]),
        "url": str(company_info["company_url"]),
        "group_id": "0",
        "check_freq": "",
        "check_day": "4",
        "depth": "100",
        "auto_reports": "1",
        "share_to": "",
        "active": "1",
        "match_mode": "subdomain",
        "color": "FFC900",
        "enable_audit": "1",
        "disable_audit": "0"
    }
    retry_count = 0
    while retry_count < 3:
        try:
            res = session.post(url, params=params, data=data, timeout=5)
        except Exception as e:
            # logger.error(f"{user['account']}: {company_info['company_name']} ----> 请求超时: {e}")
            time.sleep(random.randint(1, 2))
            retry_count += 1
            continue
        if res.status_code == 200:
            data = res.json()
            site_id = data["data"]["id"]
            group_id = get_group_id(site_id)
            # site_se_id, search_engine_id = get_site_se_id(site_id)
            if site_id and group_id:
                company_info["site_id"] = site_id
                company_info["group_id"] = group_id
                # company_info["site_se_id"] = site_se_id
                # company_info["search_engine_id"] = search_engine_id
                logger.success(f"{company_info['company_name']}: {company_info['company_url']} ------> 创建项目成功")
                return company_info
        else:
            logger.error(f"{company_info['company_name']}: 添加项目异常 -----> {res.status_code}")
            return 0

def get_group_id(site_id):
    url = "https://online.seranking.com/api.projects.se.html"
    params = {
        "do": "add"
    }
    data = {
        "engine_id": "3842",
        "region_id": "0",
        "merge_map": "0",
        "is_sum_tops_with_map_tops": "1",
        "business_name": "",
        "phone": "",
        "lang": "en",
        "safe_search": "",
        "paid_results": "0",
        "region_name": "",
        "site_id": str(site_id)
    }
    retry_count = 0
    while retry_count < 3:
        try:
            res = session.post(url, params=params, data=data, timeout=5)
        except Exception as e:
            # logger.error(f"{user['account']}: {company_info['company_name']} ----> 请求超时: {e}")
            time.sleep(random.randint(1, 2))
            retry_count += 1
            continue
        if res.status_code == 200:
            logger.success("创建搜索引擎成功")
        else:
            logger.error(f"创建搜索引擎失败 -----> {res.status_code}")
            sys.exit()
        url = "https://online.seranking.com/api.projects.wizard.html"
        params = {
            "do": "keywords",
            "site_id": site_id,
            "showSteps": "true"
        }
        res = session.get(url, params=params)
        if res.status_code == 200:
            data = res.json()
            group_id = data["data"]["default_group_id"]
            return group_id
        else:
            logger.error(res.text)
            logger.error(f"获取group_id发生异常 -----> {res.status_code}")
            return 0